package model

import (
	"github.com/jinzhu/gorm"
	gormadapter "github.com/casbin/gorm-adapter/v2"
	"github.com/casbin/casbin/v2"
)

// 用户表
type Member struct {
	ID uint64 `gorm:"column:id,primary_key;auto_increment;"`
	UserName string `gorm:"column:username;size:32;not null;default:''"`
	Password string `gorm:"column:password;type:char(32);not null;default:''"`
	Name string `gorm:"column:name;type:char(32);not null;default:''"`
	Tel string `gorm:"column:tel;type:char(20);default:''"`
	Status int `gorm:"column:status;type:tinyint(1);not null;default(1)"`
}

// 用户角色表
type MemberRole struct {
	ID uint64 `gorm:"column:id,primary_key;auto_increment;"`
	MemberID uint64 `gorm:"column:admin_id;unique_index:member_role_index;not null"`
	RoleID uint64  `gorm:"column:role_id;unique_index:member_role_index;not null"`
}

// 角色表
type Role struct {
	ID uint64 `gorm:"column:id,primary_key;auto_increment;"`
	Name string `gorm:"column:name;type:char(32);not null;default:''"`
	Desc string `gorm:"column:desc;type:char(125);not null;default:''"`
}

type RoleModule struct {
	ID uint64 `gorm:"column:id,primary_key;auto_increment;"`
	RoleID uint64  `gorm:"column:role_id;unique_index:role_module_index;not null"`
	ModuleID uint64 `gorm:"column:module_id;unique_index:role_module_index;not null"`
}

// 权限资源表
type Module struct {
	ID uint64 `gorm:"column:id,primary_key;auto_increment;"`
	Status int `gorm:"column:status;type:tinyint(1);not null;default(1)"`
	ParentID uint64 `gorm:"cloumn:parent_id;not null"`
	URL string `gorm:"column:url;size:72;default:''"`
	Name string `gorm:"column:name;type:char(32);not null;default:''"`
	OperateType string `gorm:"column:operate_type;size:32;not null;default:''"`
}

var (
	DB *gorm.DB
	Enforcer *casbin.Enforcer
)

func init() {
	// 初始化数据库
	DB, err := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/casbin")
	if err!=nil{
		panic(err)
	}
	DB.LogMode(true)
	DB.SingularTable(true)
	DB.AutoMigrate(new(Member),new(Role),new(MemberRole),new(Module),new(RoleModule))
	//初始化casbin
	a,err:=gormadapter.NewAdapterByDB(DB)
	if err!=nil{
		panic(err)
	}
	Enforcer,err=casbin.NewEnforcer("conf/rbac_models.conf", a)
	if err!=nil{
		panic(err)
	}
	err = Enforcer.LoadPolicy()
	if err!=nil{
		panic(err)
	}

	var member Member
	if DB.Where("id = ?", 1).First(&member).RecordNotFound(){
		member.ID = 0
		member.UserName = "admin"
		member.Name = "超级管理员"
		member.Password = "123456"
		member.Status = 1
		DB.Save(&member)
	}
}